package com.zx.sdk.util;

import android.os.Build;

import androidx.annotation.NonNull;

import com.google.gson.reflect.TypeToken;
import com.zx.sdk.BuildConfig;
import com.zx.sdk.ZxSDK;
import com.zx.sdk.league.member.BaseLeagueMember;
import com.zx.sdk.model.AdInfo;
import com.zx.sdk.model.Config;
import com.zx.sdk.model.Position;
import com.zx.sdk.model.Result;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

/*配置管理器*/
public class ConfigHelper {
    public static final String KEY_CONFIG = "KEY_CONFIG";
    private static Config config = new Config();//appId对应的配置
    private static Map<String, Position> positionMap;//appId对应的广告位信息配置

    /*加载配置*/
    public static void loadConfig(boolean isLogin) {
        RunnableHelper.tryRun(() -> {//从缓存里面恢复
            config = JsonHelper.from((String) SPHelper.get(KEY_CONFIG, ""), Config.class);
//            config = JsonHelper.from(ZxSDK.getContext().getResources().getString(R.string.def_ad_config), Config.class);
            if (config != null) {
                positionMap = config.getPositions();
            }
        });
        LogHelper.d("开始加载配置 appId = " + ZxSDK.getAppId() + " API_URL = " + ZxSDK.BASE_API_URL + "/api/client/config");
        HashMap<String, String> params = new HashMap<>();
        params.put("appid", ZxSDK.getAppId());
        params.put("version_code", ZxSDK.getAppVersion() + "");
        params.put("dev_token", ZxSDK.listener.getToken() + "");
        params.put("platform", "1");
        params.put("device_platform", "android");
        params.put("device_type", Build.MODEL);
        params.put("device_brand", Build.BRAND);
        params.put("os_version", Build.VERSION.RELEASE);
        params.put("mobile", ZxSDK.listener.getMobile());
        params.put("token", ZxSDK.listener.getUserToken());
        params.put("deviceId", ZxSDK.listener.getDeviceId());
        if (isLogin) {
            params.put("is_login_type", String.valueOf(1));
        }
        HttpHelper.postJSON(ZxSDK.BASE_API_URL + "/api/client/config", JsonHelper.toJson(params), new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                LogHelper.e("loadConfig postJSON", e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) {
                try {
                    Result<Config> result = getConfigFromJson(response.body().string());
                    if (result.getCode() != 2000) {
                        LogHelper.e(result.getMsg());
                        return;
                    }
                    config = result.getData();
                    positionMap = config.getPositions();
                    //放入本地缓存
                    SPHelper.put(KEY_CONFIG, JsonHelper.toJson(result.getData()));
                } catch (Throwable e) {
                    LogHelper.e("loadConfig onResponse", e);
                }
            }
        });
    }

    private static Result<Config> getConfigFromJson(String json) {
        return JsonHelper.from(json, new TypeToken<Result<Config>>() {
        }.getType());
    }

    public static ArrayList<AdInfo> getTargets(String pid) {
        Position position = getPosition(pid);
        if (position == null) return null;
        return position.getTargets();
    }

    public static int getMinBidCpm(String pid) {
        if (BuildConfig.DEBUG) {
            return -999;
        }
        Position position = getPosition(pid);
        if (position == null) return ZxSDK.Min_Bid_Cpm;
        return position.getSelfPosition().getMinBidCpm();
    }

    public static ArrayList<AdInfo> getGrounds(String pid) {
        Position position = getPosition(pid);
        if (position == null) return null;
        return position.getGrounds();
    }

    @NonNull
    public static ArrayList<AdInfo> getBidding(String pid) {
        Position position = getPosition(pid);
        if (position == null) return new ArrayList<>();
        return position.getBidding();
    }

    private static Position getPosition(String pid) {
        if (positionMap == null) {
            loadConfig(false);
            return null;
        }
        if (!MapHelper.contains(positionMap, pid)) {
            LogHelper.d("配置中没有 pid = " + pid + " 的Position配置");
            return null;
        }
        return positionMap.get(pid);
    }

    public static String getMobPidByLeaguePid(String leaguePid) {
        for (Map.Entry<String, Position> entry : positionMap.entrySet()) {
            Position value = entry.getValue();
            // 添加所有联盟位
            List<AdInfo> list = new ArrayList<>(value.getBidding());
            list.addAll(value.getTargets());
            list.addAll(value.getGrounds());

            // 遍历对比，拿到 mobPid
            for (AdInfo target : list) {
                if (leaguePid.equals(target.getMapPid())) {
                    return entry.getKey();
                }
            }
        }
        return "";
    }

    public static int getClusterCount() {
        try {
            return Integer.parseInt(config.getClusterCount());
        } catch (Throwable e) {
            return 1000;
        }
    }

    public static int getFrozenSec() {
        try {
            return Integer.parseInt(config.getFrozenSec());
        } catch (Throwable e) {
            return 30;
        }
    }

    public static int getClusterInterval() {
        try {
            return Integer.parseInt(config.getClusterInterval());
        } catch (Throwable e) {
            return 500;
        }
    }

    public static int getDmRewardTime() {
        try {
            return config.getDmRewardTime();
        } catch (Throwable e) {
            return 15;
        }
    }

    public static int getRewardPidIgnorePrice() {
        try {
            return Integer.parseInt(config.getRewardPidIgnorePrice()) * 100;
        } catch (Throwable e) {
            return 0;
        }
    }

    public static int getSplashPidIgnorePrice() {
        try {
            return Integer.parseInt(config.getSplashPidIgnorePrice()) * 100;
        } catch (Throwable e) {
            return 1000 * 100;
        }
    }

    public static float getSplashWaitSec() {
        try {
            return Float.parseFloat(config.getSplashLoadingSec());
        } catch (Throwable e) {
            return 2;
        }
    }

    public static float getFrozenFactor() {
        try {
            return Float.parseFloat(config.getFrozenFactor());
        } catch (Throwable e) {
            LogHelper.d("getFrozenFactor " + e.getMessage());
            return 1;
        }
    }

    public static int getMaxFrozenHour() {
        try {
            return Integer.parseInt(config.getMaxFrozenHour());
        } catch (Throwable e) {
            LogHelper.d("getMaxFrozenHour " + e.getMessage());
            return 24;
        }
    }

    public static int getEvent_sample_rate() {
        try {
            return Integer.parseInt(config.getEvent_sample_rate());
        } catch (Throwable e) {
            LogHelper.d("getEvent_sample_rate " + e.getMessage());
            return 0;
        }
    }

    public static float getExchangeRate() {
        try {
            return config.getUsdcny();
        } catch (Throwable e) {
            LogHelper.d("getExchangeRate " + e.getMessage());
            return 6.7F;
        }
    }

    public static boolean needWarningTips(BaseLeagueMember<?, ?, ?, ?, ?> member) {
        return config.getWarningTips().contains(member.getName());
    }

    public static ArrayList<String> getShowInterstitialPages() {
        if (config == null) {
            return new ArrayList<>();
        }
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        long lastTimeShowIllustration = SPHelper.getSp().getLong(dateFormat + "lastTimeShowIllustration", 0);
        int showIllustrationCount = SPHelper.getSp().getInt(dateFormat + "showIllustrationCount", 0);
        long interval = (System.currentTimeMillis() - lastTimeShowIllustration) / 1000;
        if (showIllustrationCount >= config.IllustrationCount || interval <= config.IllustrationIntervalSec) {
            LogHelper.d("getShowInterstitialPages", "次数上限或间隔时间未到，返回空", "interval", interval + "", "showIllustrationCount", showIllustrationCount + "");
            return new ArrayList<>();
        }
        return config.getShowInterstitialPages();
    }

    public static boolean canShowBanner() {
        if (config == null) {
            return false;
        }
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        long lastTimeShowBanner = SPHelper.getSp().getLong(dateFormat + "lastTimeShowBanner", 0);
        int showBannerCount = SPHelper.getSp().getInt(dateFormat + "showBannerCount", 0);
        long interval = (System.currentTimeMillis() - lastTimeShowBanner) / 1000;
        if (showBannerCount >= config.bannerCount || interval <= config.bannerTime) {
            LogHelper.d("canShowBanner", "次数上限或间隔时间未到，返回空", "interval", interval + "", "showBannerCount", showBannerCount + "");
            return false;
        }
        return true;
    }

    public static void showInterstitial() {
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        SPHelper.put(dateFormat + "lastTimeShowIllustration", System.currentTimeMillis());
        int showIllustrationCount = SPHelper.getSp().getInt(dateFormat + "showIllustrationCount", 0);
        SPHelper.put(dateFormat + "showIllustrationCount", ++showIllustrationCount);
        LogHelper.d("Config.showInterstitial", "dateFormat", dateFormat, "lastTimeShowIllustration", System.currentTimeMillis() + "", "showIllustrationCount", showIllustrationCount + "");
    }

    public static Boolean canShowSuspension() {
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        long lastTimeShowSuspension = SPHelper.getSp().getLong(dateFormat + "lastTimeShowSuspension", 0);
        int showSuspensionCount = SPHelper.getSp().getInt(dateFormat + "showSuspensionCount", 0);
        long interval = (System.currentTimeMillis() - lastTimeShowSuspension) / 1000;
        if (showSuspensionCount >= config.suspensionCount || interval <= config.suspensionSec) {
            LogHelper.d("isShowSuspension", "次数上限或间隔时间未到，返回空", "interval", interval + "", "showSuspensionCount", showSuspensionCount + "");
            return false;
        }
        return true;
    }

    public static void closeSuspension() {
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        SPHelper.put(dateFormat + "lastTimeShowSuspension", System.currentTimeMillis());
        int showSuspensionCount = SPHelper.getSp().getInt(dateFormat + "showSuspensionCount", 0);
        SPHelper.put(dateFormat + "showSuspensionCount", ++showSuspensionCount);
        LogHelper.d("Config.showSuspension", "dateFormat", dateFormat, "lastTimeShowSuspension", System.currentTimeMillis() + "", "showSuspensionCount", showSuspensionCount + "");
    }

    public static boolean isLogPushSwitch() {
        try {
            return config.isLogPushSwitch();
        } catch (Throwable e) {
            return false;
        }
    }

    public static void showBanner() {
        String dateFormat = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault()).format(new Date());
        SPHelper.put(dateFormat + "lastTimeShowBanner", System.currentTimeMillis());
        int showBannerCount = SPHelper.getSp().getInt(dateFormat + "showBannerCount", 0);
        SPHelper.put(dateFormat + "showBannerCount", ++showBannerCount);
        LogHelper.d("Config.showBanner", "dateFormat", dateFormat, "lastTimeShowBanner", System.currentTimeMillis() + "", "showBannerCount", showBannerCount + "");
    }
}